/**
 * Created by PanJiaChen on 16/11/18.
 */
import store from '@/store'
/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string')) {
      if ((/^[0-9]+$/.test(time))) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach(v => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}
/**
 * @param {string} feild
 * @returns {number}
 */
export function arraySort(feild) {
  return function (a, b) {
    var value1 = a[feild]
    var value2 = b[feild]
    return value1 - value2
  }
}

export function formatDate() {
   let date = new Date(); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
   let Y = date.getFullYear();
   let M = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
   let D = date.getDate();
   let H = date.getHours();
   let dateStr = Y + '' + M + D + H;
   return dateStr;
  }

//文件下载
export function fileExport(res, fileName, type) {
  const blob = new Blob([res]); //处理文档流
  let objectUrl = URL.createObjectURL(blob);
  const elink = document.createElement("a");
  elink.download = fileName + '.' + type; //下载文件名称,
  elink.style.display = "none";
  elink.href = objectUrl;
  document.body.appendChild(elink);
  elink.click();
  URL.revokeObjectURL(elink.href); // 释放URL 对象
  document.body.removeChild(elink);
}


// 过滤字典
export function filterDataDictionay(list,value){
  return list.filter((x) => {
    if (
      (x.dicValueState == 1 && (x.isDelete == undefined || x.isDelete == 0)) ||
      x.dicValueCode == value
    ) {
      return x;
    }
  });
}

// 过滤规格编码
export function filterSpecifications(list,value){
  return list.filter((x) => {
    if (
      (x.isDisable == 0 && (x.isDelete == undefined || x.isDelete == 0)) ||
      x.specificationCode == value
    ) {
      return x;
    }
  });
}

//根据身份证号获取日期、性别、年龄
export function IdCard(IdCard, type) {
  if (type === 1) {
    //获取出生日期
    let birthday = IdCard.substring(6, 10) + "-" + IdCard.substring(10, 12) + "-" + IdCard.substring(12, 14)
    return birthday
  }
  if (type === 2) {
    //获取性别
    if (parseInt(IdCard.substr(16, 1)) % 2 === 1) {
      return "男"
    } else {
      return "女"
    }
  }
  if (type === 3) {
    //获取年龄
    var ageDate = new Date()
    var month = ageDate.getMonth() + 1
    var day = ageDate.getDate()
    var age = ageDate.getFullYear() - IdCard.substring(6, 10) - 1
    if (IdCard.substring(10, 12) < month || IdCard.substring(10, 12) === month && IdCard.substring(12, 14) <= day) {
      age++
    }
    if (age <= 0) {
      age = 1
    }
    return age
  }
}

// 存储单位换算按KB 、M、 G显示字节大小
export function formatbytes(bytes) {
  const byt = bytes * 1024 // 由于后端返回的是KB 所以*1024 先转换成字节大小，在换算单位
  if (byt === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
  const i = Math.floor(Math.log(byt) / Math.log(k))
  return (byt / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i]
}

/**
 ** 加法函数，用来得到精确的加法结果
 ** 说明：javascript的加法结果会有误差，在两个浮点数相加的时候会比较明显。这个函数返回较为精确的加法结果。
 ** 调用：accAdd(arg1,arg2)
 ** 返回值：arg1加上arg2的精确结果
 **/
export function accAdd(arg1, arg2) {
  var r1, r2, m, c
  try {
    r1 = arg1.toString().split('.')[1].length
  } catch (e) {
    r1 = 0
  }
  try {
    r2 = arg2.toString().split('.')[1].length
  } catch (e) {
    r2 = 0
  }
  c = Math.abs(r1 - r2)
  m = Math.pow(10, Math.max(r1, r2))
  if (c > 0) {
    var cm = Math.pow(10, c)
    if (r1 > r2) {
      arg1 = Number(arg1.toString().replace('.', ''))
      arg2 = Number(arg2.toString().replace('.', '')) * cm
    } else {
      arg1 = Number(arg1.toString().replace('.', '')) * cm
      arg2 = Number(arg2.toString().replace('.', ''))
    }
  } else {
    arg1 = Number(arg1.toString().replace('.', ''))
    arg2 = Number(arg2.toString().replace('.', ''))
  }
  return (arg1 + arg2) / m
}

/**
 ** 减法函数，用来得到精确的减法结果
 ** 说明：javascript的减法结果会有误差，在两个浮点数相减的时候会比较明显。这个函数返回较为精确的减法结果。
 ** 调用：accSub(arg1,arg2)
 ** 返回值：arg1加上arg2的精确结果
 **/
function accSub(arg1, arg2) {
  var r1, r2, m, n
  try {
    r1 = arg1.toString().split('.')[1].length
  } catch (e) {
    r1 = 0
  }
  try {
    r2 = arg2.toString().split('.')[1].length
  } catch (e) {
    r2 = 0
  }
  m = Math.pow(10, Math.max(r1, r2)) // last modify by deeka //动态控制精度长度
  n = (r1 >= r2) ? r1 : r2
  return ((arg1 * m - arg2 * m) / m).toFixed(n)
}

/**
 ** 乘法函数，用来得到精确的乘法结果
 ** 说明：javascript的乘法结果会有误差，在两个浮点数相乘的时候会比较明显。这个函数返回较为精确的乘法结果。
 ** 调用：accMul(arg1,arg2)
 ** 返回值：arg1乘以 arg2的精确结果
 **/
export function accMul(arg1, arg2) {
  var m = 0;
  var s1 = arg1.toString();
  var s2 = arg2.toString()
  try {
    m += s1.split('.')[1].length
  } catch (e) {
    console.log()
  }
  try {
    m += s2.split('.')[1].length
  } catch (e) {
    console.log()
  }
  return Number(s1.replace('.', '')) * Number(s2.replace('.', '')) / Math.pow(10, m)
}

/**
 * 输入框限制输入 只允许输入数字
 * value 数值 必填
 * max 最大值 选填
 * min 最小值 选填
 * length 小数点保留位数 选填
 * isBlur 失去焦点触发
 */
export function limitInputNumber(value, max = null, min = null, length = null, isBlur = false, isMoney = false) {
  // if (value <= 0) {
  //   return 1
  // }
  if (!value && value !== 0) {
    return min >= 0 ? min : null
  }
  // 是否需要保留小数
  value = value.toString()
  if (!length) {
    if (max < 0 || min < 0) {
      value = value.replace(/[^\-\d]+/g, '')
    } else {
      value = value.replace(/[^0-9]/ig, '')
    }
  } else {
    // 保留数字和小数点
    if (max < 0 || min < 0) {
      value = value.replace(/[^\-\d^\.]+/g, '')
    } else {
      value = value.replace(/[^\d^\.]+/g, '')
    }
    if (value.indexOf('.') > 0) {
      value = value.slice(0, value.indexOf('.') + (length + 1))
    } else if (value.indexOf('.') === 0 && value.length === 1) {
      value = 0 + value
    } else if (value.indexOf('.') === value.length - 1 && value.length != 0 && isBlur) {
      value = value.substring(0, value.length - 1)
    }
  }
  if (max) {
    max = Number(max)
    const tempValue = Number(value)
    if (tempValue > max) {
      value = max
    }
  }
  if (min) {
    min = Number(min)
    const tempValue = Number(value)
    if (tempValue <= min) {
      value = 1
    }
  }
  if (isMoney) {
    for (var i = 0; i < value.length; i++) {
      if (value[i] === '.') {
        break
      }
      if (value[i] == 0 && value[i + 1] !== '.' && i == 0) {
        value = value.slice(i + 1, value.length - 1)
        i--
      }
    }
  }
  if (isBlur) {
    return Number(value)
  } else {
    return value
  }
}

// 匹配下拉数据
export function querySelectName(data,code,label,value){
  let name
  data.forEach((item)=>{
    if(item[value] == code){
      name = item[label]
    }
  })
  return name
}

/**
 *权限控制
 */
export function hasPermission(value) {
  let isExist = false;
  // 从配置获取用户按钮权限
  let btnPermissions = store.getters.userInfo.buttons
  // 从配置获取用户按钮权限
  if (btnPermissions && btnPermissions.length > 0) {
    let index = btnPermissions.findIndex(item =>
      item == value
    )
    if (index > -1) {
      isExist = true
    }
    return isExist;
  }
}

export function empty(e) {
  switch (e) {
    case "":
    case null:
    case false:
    case undefined:
      return false;
    default:
      return true;
  }
}